package com.laogao.lesson016.controller;

import com.laogao.lesson016.common.Result;
import com.laogao.lesson016.common.ResultUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * <b>description</b>： Java进阶、性能优化实战案例100讲，微信公众号:程序员恰恰，源码 & 文档 & 技术支持，请加个人微信号：it3306 <br>
 * <b>time</b>：2025/4/10 14:44 <br>
 * <b>author</b>：ready lao_gao
 */
@RestController
public class HelloController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @GetMapping("/ok")
    public Result<String> hello() throws InterruptedException {
        logger.info("开始执行业务");
        TimeUnit.MILLISECONDS.sleep(500);
        logger.info("业务执行结束");
        return ResultUtils.success("欢迎和老高一起学习《高并发 & 微服务 & 性能调优实战案例100讲》");
    }

    @GetMapping("/exception")
    public Result<String> exception() throws InterruptedException {
        logger.info("开始执行业务");
        //这里模拟了一个错误，10/0，会报错
        System.out.println(10 / 0);
        logger.info("业务执行结束");
        return ResultUtils.success("欢迎和老高一起学习《高并发 & 微服务 & 性能调优实战案例100讲》");
    }

    @GetMapping("/sync")
    public Result<String> sync() throws InterruptedException {
        //String traceId = TraceUtils.getTraceId();
        CompletableFuture.runAsync(() -> {
            try {
                System.out.println(10 / 0);
            } catch (Exception e) {
                // 显式打印异常
                e.printStackTrace();
            }
        });
        return ResultUtils.success("欢迎和老高一起学习《高并发 & 微服务 & 性能调优实战案例100讲》");
    }

    @GetMapping("/child")
    public Result<String> child() throws InterruptedException {
        new Thread(() -> {
            System.out.println(10 / 0);
        }, "thread1").start();
        TimeUnit.SECONDS.sleep(1);
        return ResultUtils.success("欢迎和老高一起学习《高并发 & 微服务 & 性能调优实战案例100讲》");
    }
}
